package com.lxx.interceptor;

import javax.servlet.http.HttpServletRequest;
import static com.lxx.utils.Constant.SESSION_USER_FLAG;

import java.util.List;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.lxx.common.ErrCode;
import com.lxx.modules.sys.entity.SysPermission;

import static com.lxx.utils.ResponseUtils.writeJson2Header;

import com.lxx.utils.Config;
import com.lxx.utils.SessionInfo;
import com.lxx.utils.SessionUtils;

public class AuthInterceptor extends HandlerInterceptorAdapter{
	
	private static final Logger LOGGER = LoggerFactory.getLogger(AuthInterceptor.class);
	
	private Config config;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		HttpSession session = request.getSession();
		StringBuffer uri = new StringBuffer(request.getRequestURI());
		if (uri.indexOf("/user/toPage") != -1) {
			uri.append('?').append(request.getQueryString());
			LOGGER.info("{} - {}", session.getId(), uri);
			return true;
		}
		LOGGER.info("{} - {}", session.getId(), uri);
		
		if ("false".equalsIgnoreCase(config.getOpen())) {
			return true;
		}
		
		if (!SessionUtils.isLogged(session)) {
			writeJson2Header(response, ErrCode.NOT_LOGGED_IN);
			LOGGER.info("用户未登陆");
			return false;
		}
		
		String url = StringUtils.substringBeforeLast(request.getServletPath(), ".");
		
		SessionInfo o = (SessionInfo) session.getAttribute(SESSION_USER_FLAG);
		List<SysPermission> perms = o.getUser().getPermissions();
		for (SysPermission sysPermission : perms) {
			if (StringUtils.isNotBlank(sysPermission.getUrl()) && sysPermission.getUrl().equals(url)) {
				return true;
			}
		}
		
		writeJson2Header(response, ErrCode.NO_PERMISSION);
		LOGGER.info("没有访问权限");
		return false;
	}

	public Config getConfig() {
		return config;
	}

	public void setConfig(Config config) {
		this.config = config;
	}
}
